package net.sf.ivyide.idea;

import com.intellij.openapi.progress.ProgressIndicator;
import fr.jayasoft.ivy.ModuleId;
import net.sf.ivyide.DependencyType;
import net.sf.ivyide.ModuleManager;
import net.sf.ivyide.ResolvedModule;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class ModuleResolver {

    public List<ResolvedModule> getResolvedModules(ModuleManager moduleManager, ProgressIndicator indicator) {
        indicator.setIndeterminate(false);
        indicator.setText("Resolving modules");
        indicator.setText2("root module");
        indicator.setFraction(0.001);
        double maxResolves = moduleManager.getAmountOfSourceModules() + 1;//also include root module
        double resolvedCount = 0;
        ResolvedModule rootModule = moduleManager.resolveModule(moduleManager.getRootModuleDir());
        rootModule.checkResolveErrors();
        indicator.setFraction(++resolvedCount / maxResolves);
        List<ResolvedModule> results = new LinkedList<ResolvedModule>();
        results.add(rootModule);
        Map<ModuleId, DependencyType> internalModules = moduleManager.getDependantModules(rootModule);
        for (ModuleId moduleId : internalModules.keySet()) {
            if (DependencyType.SOURCE.equals(internalModules.get(moduleId))) {
                final File file = moduleManager.getModules().get(moduleId);
                indicator.setText2(moduleId.getName());
                ResolvedModule resolvedModule = moduleManager.resolveModule(file);
                resolvedModule.checkResolveErrors();
                results.add(resolvedModule);
                indicator.setFraction(++resolvedCount / maxResolves);
            }
        }
        //Collections.sort(results);
        //Collections.reverse(results);
        indicator.setIndeterminate(true);
        indicator.setText2("");
        return results;
    }

}
